LINQ to XML - Transform Samples


LINQ, LINQ to XML, .NET Framework 4.0
LINQ, LINQ to XML, XML, Console Window, XML Documentation
Desktop, Data
en-US
6/28/2011

Introduction

These samples show how to transform XML data into HTML code.

Building the Sample

  1. Open Program.cs
  2. Uncomment the line for the sample that you want to run; comment ones you don't want to run
  3. Press Ctrl + F5

Screenshot

Sample Code

C#
Edit|Remove
            [Category("Transform")] 
            [Description("Generate html with a list of customers that is numbered")] 
            public void XLinq77() 
            { 
                XDocument doc = XDocument.Load("nw_customers.xml"); 
 
                var header = new[]{                  
                    new XElement("th","#"), 
                    new XElement("th", 
                                 "customer id"), 
                    new XElement("th", 
                                 "contact name")}; 
                int index = 0; 
                var rows = 
                    from 
                        customer in doc.Descendants("Customers") 
                    select 
                        new XElement("tr", 
                                     new XElement("td", 
                                                  ++index), 
                                     new XElement("td", 
                                                  (string)customer.Attribute("CustomerID")), 
                                     new XElement("td", 
                                                  (string)customer.Element("ContactName"))); 
 
                XElement html = new XElement("html", 
                                      new XElement("body", 
                                        new XElement("table", 
                                          header, 
                                          rows))); 
                Console.Write(html); 
            }

Source Code Files

More Information

For more information on LINQ to XML: http://msdn.microsoft.com/en-us/library/bb387098.aspx